import store from '@/store'
import router from '@/router'
import NProgress from 'nprogress'// 进度条插件
import 'nprogress/nprogress.css'// 进度条插件样式
import { asyncRoutes } from '@/router/index'

const write = ['/login', '/404']
router.beforeEach(async(to, from, next) => {
  const token = store.getters.token
  NProgress.start()
  if (token) {
    if (to.path === '/login') {
      next('/')
      NProgress.done()
    } else {
      // 进页面之前先请求一下用户名(加await 先请求在跳转)
      if (Object.keys(store.state.user.infor) <= 0) {
        // const res = await store.dispatch('user/setinfor')
        // console.log(res)
        const { roles: { menus }} = await store.dispatch('user/setinfor')
        // 1.先筛选出符合条件的路由规则
        // 根据asyncRoutes 和menus 先筛选
        const otherRoutes = asyncRoutes.filter(item => {
          return menus.includes(item.children[0].name)
        })
        // console.log(otherRoutes)
        // 存到vuex中(存到vuex中的数据，为了展示侧边栏，404不写到vuex也可以 因为404不需要展示到侧边栏)
        // store.commit('permission/setRoutes', otherRoutes)
        store.commit('permission/setRoutes', [...otherRoutes, { path: '*', redirect: '/404', hidden: true }])
        // 2.动态添加符合条件的路由规则
        // router.addRoutes(otherRoutes)
        // 这个数据是为了可以跳转路由
        router.addRoutes([...otherRoutes, { path: '*', redirect: '/404', hidden: true }])
        next({
          ...to,
          replace: true
        })
        return
      }
      next()
      NProgress.done()
    }
  } else {
    if (write.includes(to.path)) {
      next()
      NProgress.done()
    } else {
      next('/login')
      NProgress.done()
    }
  }
})

router.afterEach((to, from) => {
  NProgress.done()
})
